//递归获取 views 文件夹下的所有.vue文件
const files = require.context('@/views', true, /\.vue$/)
let page = {};
files.keys().forEach(key => {
  page[key.replace(/(\.\/|\.vue)/g, '')] = {
    component: files(key).default,
    children: []
  };
})
Object.keys(page).reverse().forEach(item => {
  let index = item.lastIndexOf("\/");
  let str = item.substring(0, index);
  // console.log(page[str],page[item]);
  if (str) {
    page[str].children.push(page[item])
  }
})
let pagesIndex = Object.keys(page).filter((r)=> r.indexOf("/")<0)
let pages = {}
pagesIndex.map(e => {
  pages[e] = page[e]
});
//生成路由规则
let generator = [];
let renderChildRoute = function (arr) {
  let childRoute = []
  arr.forEach(item2 => {
    childRoute.push({
      path: `${item2.component.name}`,
      name: item2.component.name,
      component: item2.component,
      meta:item2.component.meta,
      children: renderChildRoute(item2.children)
    })
  });
  return childRoute
}
Object.keys(pages).forEach(item => {  
  generator.push({
    path: `/${item}`,
    name: pages[item].component.name,
    component: pages[item].component,
    meta:pages[item].component.meta,
    children:renderChildRoute(pages[item].children)
  })
});
console.log(generator, "<--generator");
//合并公共路由以及重定向规则
const routes = [{
    path: '/',
    redirect: '/Index',
  },
  ...generator,
  {
    path: '*',
    component: () => import('@/views/404.vue'),
  }
];

export default routes;